package org.community.loginsvc.service.codeservice;


import com.sun.istack.internal.NotNull;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional(
        isolation = Isolation.REPEATABLE_READ
)
@RequiredArgsConstructor
@Data
//验证码检查服务
public class CodeCheckServiceImpl implements CodeCheckService{

    @NotNull
    private StringRedisTemplate stringRedisTemplate;


    //将验证码存入redis并返回存储id
    @Override
    public String setCode(String code) {
        String codeId = UUID.randomUUID().toString();
        StringRedisTemplate redisTemplate = this.getStringRedisTemplate();
        redisTemplate.opsForValue().set(codeId,code);
        redisTemplate.expire(codeId,30, TimeUnit.SECONDS);//验证码30s过期
        return codeId;

    }

    //从redis中取出验证码并检验是否正确
    @Override
    public boolean checkCode(String codeId, String code) {
        StringRedisTemplate redisTemplate = this.getStringRedisTemplate();
        String rightCode =  redisTemplate.opsForValue().get(codeId);
        //验证后删除指定id的键
        redisTemplate.delete(codeId);
        return code.equalsIgnoreCase(rightCode);
    }



}
